<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .wrap {
            width: 500px;
            height: 500px;
            border: 1px solid #333;
            margin: 50px auto;
            position: relative;
        }
        .box {
            width: 50px;
            height: 50px;
            background-color: #6ff;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="box"></div>
    </div>

</body>
<script>
    var wrap = document.getElementsByClassName("wrap")[0];
    var box = document.getElementsByClassName("box")[0];

    var maxLeft = wrap.clientWidth - box.clientWidth;
    var maxTop = wrap.clientHeight - box.clientHeight;

    
    wrap.onmousemove = function (e) {
        var e = e || window.event;
        var x = e.pageX - wrap.offsetLeft - box.clientWidth / 2;
        var y = e.pageY - wrap.offsetTop - box.clientHeight / 2;

        if (x < 0) x = 0;
        if (y < 0) y = 0;
        if (x > maxLeft) x = maxLeft;
        if (y > maxTop) y = maxTop;

        box.style.left = x + "px";
        box.style.top = y + "px";
    }
</script>

</html>